'use strict';

module.exports = {

	/**
	 * 删除有空值的键
	 * @method delNullKey
	 * @for 所属类名helper
	 * @param {json} obj 处理对象
	 * @return {json} 处理后的对象
	 */
	delNullKey(obj) {
		// this 就是 ctx 对象，在其中可以调用 ctx 上的其他方法，或访问属性

		var delArray = new Array();
		for(var k in obj) {
			if(obj[k] == '') {
				delArray.push(k);
			}
		}

		for(var i = 0; i < delArray.length; i++) {
			delete obj[delArray[i]];
		}

		return obj;
	},

	/**
	 * 删除无效的键
	 * @method delNullKey
	 * @for 所属类名helper
	 * @param {json} obj 处理对象
	 * @param {json} rules 比对模板，模板中的键为有效键
	 * @return {json} 处理后的对象
	 */
	delInvalidKey(obj, rules) {
		var returnObj = Object.assign({}, obj);
		var delArray = new Array();
		for(var j in returnObj) {
			var isHave = false;
			for(var i in rules) {
				if(i == j) {
					isHave = true;
					break;
				}
			}
			if(!isHave) {
				delArray.push(j);
			}
		}
		for(var i = 0; i < delArray.length; i++) {
			delete returnObj[delArray[i]];
		}

		return returnObj;
	},
	
	/**
	 * 获取uuid
	 * @method getUuid
	 * @return {string} 无【-】符号的32位随机字符串
	 */
	getUuid(){
		var uuid = require('node-uuid');
		const code = uuid.v1().replace(new RegExp("-",'g'), "");
		
		return code;
	},
	
	/**
	 * 获取guid
	 * @return {string} guid
	 */
	getGuid(num = 36) {
		var s = [];
		var hexDigits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		for (var i = 0; i < num; i++) {
			s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
		}

		s[14] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1); // bits 12-15 of the time_hi_and_version field to 0010
		s[19] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
		s[8] = s[13] = s[18] = s[23] = "-";

		var uuid = s.join("");
		console.log(uuid)
		uuid = uuid.replace(/-/g, "");
		console.log(uuid)
		return uuid;
	},
	
	// 格式化key
	formatPKCKey(key, isPrivate, isFirst) {
		var len = key.length;
		var result = isPrivate ? "-----BEGIN PRIVATE KEY-----\r\n" : "-----BEGIN PUBLIC KEY-----\r\n";

		var index = 0;
		var count = 0;

		while (index < len) {
			var ch = key[index];
			if (ch === '\r' || ch === '\n' || ch === '\r\n') {
				++index;
				continue;
			}
			result += ch;

			if (++count === 64) {
				result += '\r\n';
				count = 0;
			}
			index++;
		}
		//如果是1.0
		if (isFirst) {			
			result += "\r\n-----END RSA PRIVATE KEY-----";
		} else {
			result += isPrivate ? "\r\n-----END PRIVATE KEY-----" : "\r\n-----END PUBLIC KEY-----";
		}
//		console.log(result)
		return result;
	},
};